import React, { PureComponent, Fragment } from 'react';
import { Form, Input, Icon, Select, Modal, Spin, Alert } from 'antd';
// import { connect } from 'dva';
import moment from 'moment';
import lodash from 'lodash';
// import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { getJob, validatorCron } from '../../../services/alarm-job-controller';
import { NotificationRuleArray, TimeUnitArray } from '../../../utils/enum';
// import classNames from 'classnames';
import styles from './JobBasicConfigAdd.less';

@Form.create()
export default class JobBasicConfigAdd extends PureComponent {

  state = {
    showTheSampleCron: false,
    theSampleCron: [
      { cron: '*/5 * * * * ?', description: '每5秒钟执行一次' },
      { cron: '* 0/1 * * * ?', description: '每一分钟执行一次' },
      { cron: '* * 0/2 * * ?', description: '每两个小时执行一次' },
      { cron: '0 0 0 1-15 * ? *', description: '每个月1-15号的0:00:00执行一次' },
      { cron: '0 0 12 ? * WED', description: '每个星期三中午12点' },
      { cron: '0 15 10 * * ? 2005', description: '2005年的每天上午10:15触发' },
      { cron: '0 15 10 L * ?', description: '每月最后一日的上午10:15触发' },
    ],

    showValidatorCronModal: false,
    validatorCronLoading: false,
    showValidatorCronData: [],
  }

  showValidatorCron = () => {
    const { form: { getFieldValue } } = this.props;
    const cron = getFieldValue('cron');
    if (lodash.trim(cron) !== '') {
      this.setState({ validatorCronLoading: true, showValidatorCronModal: true });
      validatorCron({ cron, num: 15 }).then(res => this.setState({ validatorCronLoading: false, showValidatorCronData: res }))
        .catch(() => this.setState({ validatorCronLoading: false, showValidatorCronData: [] }));
    }
  }

  render() {
    const { showTheSampleCron, theSampleCron, showValidatorCronModal, validatorCronLoading, showValidatorCronData } = this.state;
    const { jobConfigData, saveForm, isEdit = false, form } = this.props;
    const { getFieldDecorator, getFieldValue } = form;
    if (saveForm instanceof Function) saveForm(form);
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 },
        md: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
        md: { span: 12 },
      },
    };
    // const submitFormLayout = {
    //   wrapperCol: {
    //     xs: { span: 24, offset: 0 },
    //     sm: { span: 18, offset: 3 },
    //     md: { span: 12, offset: 7 },
    //   },
    // };
    const rule = getFieldValue('rule');
    return (
      <Fragment>
        <Form layout="horizontal" className={styles.form}>
          <Form.Item label="告警名称" hasFeedback {...formItemLayout}>
            {getFieldDecorator('name', {
              initialValue: jobConfigData ? jobConfigData.name : undefined,
              validateFirst: true,
              rules: [
                { required: true, whitespace: false, min: 3, max: 63, message: '告警名称长度必须3~63字符' },
                {
                  validator(_, value, callback) {
                    if (!value || lodash.trim(value) === '') {
                      callback(["告警名称不能为空"]);
                      return;
                    }
                    if (isEdit && jobConfigData && jobConfigData.name === value) {
                      callback([]);
                      return;
                    }
                    getJob(value).then(result => {
                      if (result) {
                        callback(["告警名称重复"]);
                      } else {
                        callback([]);
                      }
                    }).catch(() => callback([]));
                  },
                },
              ],
            })(
              <Input placeholder="告警名称" disabled={isEdit} />
            )}
          </Form.Item>

          <Form.Item label="Cron表达式" {...formItemLayout}>
            {getFieldDecorator('cron', {
              initialValue: jobConfigData ? jobConfigData.cron : undefined,
              validateFirst: true,
              rules: [
                { required: true, whitespace: false, min: 11, max: 127, message: 'Cron表达式至少有11个字符' },
                {
                  validator(_, value, callback) {
                    if (!value || lodash.trim(value) === '') {
                      callback(["Cron表达式不能为空"]);
                      return;
                    }
                    validatorCron({ cron: value, num: 5 }).then(result => {
                      if (!result) {
                        callback(["Cron表达式错误"]);
                      } else {
                        callback([]);
                      }
                    }).catch(() => callback([]));
                  },
                },
              ],
            })(
              <Input
                placeholder="Cron表达式，如：0 */1 * * * ?"
                addonBefore={(
                  <Icon style={{ cursor: 'pointer' }} type="info-circle" theme="outlined" title="示例" onClick={() => this.setState({ showTheSampleCron: true })} />
                )}
                addonAfter={(
                  <Icon style={{ cursor: 'pointer' }} type="clock-circle" theme="outlined" title="验证" onClick={this.showValidatorCron} />
                )}
              />
            )}
          </Form.Item>

          <Form.Item label="通知规则" {...formItemLayout}>
            {getFieldDecorator('rule', {
              initialValue: jobConfigData ? jobConfigData.rule : undefined,
              validateFirst: true,
              rules: [
                { required: true, whitespace: false, message: '通知规则不能为空' },
              ],
            })(
              <Select placeholder="通知规则" allowClear={false}>
                {NotificationRuleArray.map(item => (<Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>))}
              </Select>
            )}
          </Form.Item>

          {rule === 'frequency' ? (
            <Fragment>
              <Form.Item label="频率时间段" required {...formItemLayout}>
                {getFieldDecorator('frequencyTimeLength', {
                  initialValue: jobConfigData ? jobConfigData.frequencyTimeLength : undefined,
                  validateFirst: true,
                  rules: [
                    {
                      validator(_, value, callback) {
                        if (!value || lodash.trim(value) === '') {
                          callback(["Cron表达式不能为空"]);
                          return;
                        }
                        callback([]);
                      },
                    },
                  ],
                })(
                  <Input
                    placeholder="频率时间段(必须是整数)"
                    addonAfter={
                      getFieldDecorator('frequencyTimeLengthUnit', { initialValue: 'second' })(
                        <Select style={{ width: 70 }}>
                          {TimeUnitArray.map(item => (<Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>))}
                        </Select>
                      )
                    }
                  />
                )}
              </Form.Item>

              <Form.Item label="告警次数上限" required {...formItemLayout}>
                {getFieldDecorator('frequencyCountMax', {
                  initialValue: jobConfigData ? jobConfigData.frequencyCountMax : undefined,
                  validateFirst: true,
                  rules: [
                    {
                      validator(_, value, callback) {
                        if (!value || lodash.trim(value) === '') {
                          callback(["Cron表达式不能为空"]);
                          return;
                        }
                        callback([]);
                      },
                    },
                  ],
                })(
                  <Input placeholder="告警次数上限(大于等于此值发送通知)" addonAfter="次" />
                )}
              </Form.Item>
            </Fragment>
          ) : ''}

          {rule === "flatline" ? (
            <Form.Item label="持续时间上限" required {...formItemLayout}>
              {getFieldDecorator('flatlineTimeLengthMax', {
                initialValue: jobConfigData ? jobConfigData.flatlineTimeLengthMax : undefined,
                validateFirst: true,
                rules: [
                  {
                    validator(_, value, callback) {
                      if (!value || lodash.trim(value) === '') {
                        callback(["Cron表达式不能为空"]);
                        return;
                      }
                      callback([]);
                    },
                  },
                ],
              })(
                <Input
                  placeholder="持续时间上限(必须是整数，大于等于此值发送通知)"
                  addonAfter={
                    getFieldDecorator('flatlineTimeLengthMaxUnit', { initialValue: 'second' })(
                      <Select style={{ width: 70 }}>
                        {TimeUnitArray.map(item => (<Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>))}
                      </Select>
                    )
                  }
                />
              )}
            </Form.Item>
          ) : ''}

          <Form.Item label="任务描述信息" {...formItemLayout}>
            {getFieldDecorator('description', {
              initialValue: jobConfigData ? jobConfigData.description : undefined,
              rules: [
                { required: false, max: 1023, message: '任务描述信息长度不能超过1023个字符' },
              ],
            })(
              <Input.TextArea placeholder="任务描述信息" rows={5} autosize={{ minRows: 5, maxRows: 10 }} />
            )}
          </Form.Item>
          {/* <Form.Item {...submitFormLayout}>
          <Button>配置监控项</Button>
        </Form.Item> */}
        </Form>
        <Modal
          title="Cron表达式示例"
          visible={showTheSampleCron}
          maskClosable={true}
          footer={null}
          onCancel={() => this.setState({ showTheSampleCron: false })}
        >
          <a href="http://cron.qqe2.com/" target="_bank" style={{ display: 'inline-block', marginBottom: 12 }}>Cron参考</a>
          {theSampleCron.map(item => (
            <div key={item.cron} style={{ marginBottom: 8 }}>
              <span style={{ display: 'inline-block', width: 130, fontWeight: 'bold' }}>{item.cron}</span>
              <span>{item.description}</span>
            </div>
          ))}
        </Modal>
        <Modal
          title={`${getFieldValue('cron')}-执行时间`}
          visible={showValidatorCronModal}
          maskClosable={true}
          footer={null}
          onCancel={() => this.setState({ showValidatorCronModal: false })}
        >
          <Spin delay={100} spinning={validatorCronLoading} wrapperClassName={styles.center}>
            {
              showValidatorCronData.length > 0 ?
                showValidatorCronData.map((time, index) => (
                  <div key={time} style={{ marginBottom: 8, width: 280 }}>
                    <span style={{ display: 'inline-block', width: 100, fontWeight: 'bold' }}>第{index + 1}次触发：</span>
                    <span>{moment(time).format('YYYY-MM-DD HH:mm:ss')}</span>
                  </div>
                )) :
                <Alert type="error" message={`Cron表达式错误：${getFieldValue('cron')}`} />
            }
          </Spin>
        </Modal>
      </Fragment>
    );
  }
}
